﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace Client.Resources
{
    public class GreyableImage : Image
    {
        static GreyableImage()
        {
            IsEnabledProperty.OverrideMetadata(typeof(GreyableImage), new FrameworkPropertyMetadata(true, new PropertyChangedCallback(OnAutoGreyScaleImageIsEnabledPropertyChanged)));
        }

        /// <summary>
        /// Changes the between original and grey icon
        /// </summary>
        /// <param name="source">AutoGreyableImage Image</param>
        /// <param name="args">Boolean IsEnabled</param>
        private static void OnAutoGreyScaleImageIsEnabledPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs args)
        {
            var autoGreyScaleImg = source as GreyableImage;
            var isEnable = Convert.ToBoolean(args.NewValue);

            if (autoGreyScaleImg != null)
            {
                // set the grey image
                if (!isEnable)
                {
                    string[] sourceArray = autoGreyScaleImg.Source.ToString().Split('.');
                    autoGreyScaleImg.Source = new BitmapImage(new Uri(sourceArray[0] + "_grey.png"));
                }
                // set the original image
                else
                {
                    string newSource = autoGreyScaleImg.Source.ToString().Replace("_grey", string.Empty);
                    autoGreyScaleImg.Source = new BitmapImage(new Uri(newSource));
                }
            }
        }
    }
}